<?php
// 接口-委外入库检验
namespace interface\v1;

use verify;
use control\optionSettingClass;

class outsourceInspectionClass extends index
{
	private const page  = 'outsourceInspection';
	private const table = 'quality_order';
	private const title = '委外入库检验';

	public function search()
	{
		$this->code         = 1;
		$this->resp['data'] = [
			'orderNo' => '单据条码',
			'state'   => [
				'待质检', '已质检',
			],
		];
	}

	/**
	 * 列表
	 *
	 * @return void
	 */
	public function list(): void
	{
		//获取查询结果
		$where = " a.type = 5 ";
		$where .= search([
			"="    => [
				'a.coid' => self::$coid,
			],
			'like' => [
				'a.orderNo' => $this->post('orderNo'),
			],
			"in"   => [
				'a.state' => $this->post('state') ? (($this->post('state') === '待质检') ? ['待质检', '草稿'] : [$this->post('state')]) : ['待质检', '草稿'],
			],
		]);

		$page = $this->page([
			"table" => self::table . " as a join material as b on a.materialId = b.id",
			'field' => "a.*, b.name, b.code, b.model",
			"where" => $where,
			"order" => " a.time desc, a.list asc",
		]);
		//数据分析
		$data['title']  = ["单据日期", "单据编号", "供应商", "物料编码", '物料名称', '规格型号', '单位', '批次', '收货数量', '合格数量', '不良数量', '状态', '质检日期'];
		$data['result'] = [];
		foreach ($page['array'] as $array) {
			$supplier           = query('supplier', "id = '$array[targetId]'");
			$outsource_in_order = query('outsource_in_order', "id = '$array[sourceId]'");
			$data['result'][]   = [
				"id"           => $array['id'],
				'sourceNo'     => $array['sourceNo'],
				'recordDate'   => $outsource_in_order['recordDate'],
				'code'         => $array['code'],
				'material'     => $array['name'] . ($array['model']?' - ' .$array['model'] :''),
				'supplierName' => $supplier['name'],
				'batch'        => $array['batch'],
				'num'          => self::lostZero($array['num'], 'numPrecision'),
				'passNum'      => self::lostZero($array['passNum'], 'numPrecision'),
				'badNum'       => $array['state'] == '待质检' ? 0 : $array['num'] - $array['passNum'],
				"state"        => $array['state'],
				'checkTime'    => self::null($array['checkTime']),
				'time'         => self::formatDate($array['time'], 'Y/m/d'),
			];
		}
		$data['page'] = $page['para'];
		//返回
		$this->code         = 1;
		$this->resp['data'] = $data;
	}

	/*详情页*/
	public function detail()
	{
		$info = query(self::table, " id = '{$this->post('id')}'");
		if (empty($info['id'])) {
			$this->resp['warn'] = '未找到此' . self::title;
		} else {
			/*****质检项目********/
			$quarantineItem['title']  = ['质检项', '检验标准', '结果选项', '备注'];
			$result                   = find(array('table' => self::table . "_item", 'where' => "orderId = '$info[id]' order by list"));
			$quarantineItem['result'] = [];
			foreach ($result['array'] as $array) {
				$quarantine_item            = query('quarantine_item', "id = '$array[itemId]'");
				$quarantineItem['result'][] = [
					'itemId'   => $array['id'],
					'name'     => $quarantine_item['name'],
					'standard' => $quarantine_item['standard'],
					'option'   => explode('，', $quarantine_item['result']),
					'checked'  => $quarantine_item['result'],
					'itemText' => $array['text'],
				];
			}

			/*****不良原因********/
			$reason['title'] = ['不良原因', '不良数量', '处置方式', '备注', '状态', '处理人', '处理日期', '操作'];
            $reason['result'] = [];
			$result          = find(array('table' => self::table . "_reason", 'where' => "orderId = '$info[id]' order by list"));
			foreach ($result['array'] as $array) {
				$reason['result'][] = [
					'reasonId'     => $array['id'],
					'reasonOption' => find([
						'table' => 'quarantine_reason',
						'where' => " coid = '" . self::$coid . "' and orderId = '$info[qid]' order by list asc ",
						'field' => ' id as value,  reason as text',
					])['array'],
					'reasonNum'    => self::lostZero($array['num'], 'numPrecision'),
					'mxText'       => $array['text'],
					'state'        => $array['state'],
					'dealStaff'    =>
						self::findStaff($array['dealId']),
					'dealDate'     => self::null($array['dealDate']),
				];
			}
			$kehu        = query('kehu', "khid = '$info[targetId]'");
			$source      = query($info['sourceTable'], "id = '$info[sourceId]'");
			$material    = query('material', "id = '$info[materialId]'");
			$quarantine  = query('quarantine', "id = '$info[qid]'");
			$setting     = optionSettingClass::getSetting('质量');
			if ($info['updateTime'] == $info['time'] && $info['state'] == '待质检' && isset($setting['checkOrderDefault']['val']) && $setting['checkOrderDefault']['val'] == '单据数量') {
				$info['passNum'] = $info['num'];
			}
			$this->resp['data'] = [
				'info'       => [
					"id"          => $array['id'],
					'recordDate'  => $source['recordDate'], //单据日期
					'sourceNo'    => $info['sourceNo'], // 单据编号
					'companyName' => $kehu['companyName'], //客户
					'code'        => $material['code'], //物料编码
					'name'        => $material['name'], //物料名称
					'model'       => $material['model'], //规格型号
					'material'    => $material['code'] . '-' . $material['name'] . '-' . $material['model'],
					'batch'       => $info['batch'], // 批次
					'unit'        => $info['unit'], //单位
					'num'         => self::lostZero($info['num'], 'numPrecision'), //完工数量
					'passNum'     => self::lostZero($info['passNum'], 'numPrecision'), //合格数量
					'badNum'      => $info['state'] == '待质检' ? 0 : $info['num'] - $info['passNum'], //不良数量
					"state"       => $info['state'],
					'checkTime'   => $info['checkTime'],
					'time'        => self::formatDate($info['time'], 'Y/m/d'),
				],
				'quality'    => [
					"qualityType"    => $quarantine['qualityType'],
					"proportionRate" => ($quarantine['proportion'] * 100) . '%',
					"proportionNum"  => $info['num'] * $quarantine['proportion'],
					'mandate'        => $quarantine['mandate'],
				],
				'quarantine' => $quarantineItem,
				'reason'     => $reason,
				'system'     => [
					"orderNo"    => $info['orderNo'],
					"checkStaff" => self::findStaff($info['checkId']),
					"checkId"    => $info['checkId'],
					"checkTime"  => $info['checkTime'],
				],
			];
			$this->code         = 1;
		}
	}

	/**
	 * 提交
	 *
	 * @return bool|string
	 */
	public function detailEdit()
	{
        $detail = !empty($_POST['detail']) ? json_decode($_POST['detail'], true) : [];
        $id = $this->post('id');
        $itemTextArr = $this->post('itemText');
        $itemIdArr = $this->post('resultOption') ? array_keys($this->post('resultOption')) : [];
        $resultOptionArr = $this->post('resultOption');
        $reasonIdArr = inStockClass::getArrVal('reasonOptionId', $detail);
        $reasonNumArr = inStockClass::getArrVal('reasonNum', $detail);
        $mxTextArr = inStockClass::getArrVal('mxText', $detail);

		$field      = [
			'state'     => '已质检',
			'checkId'   => self::$stid,
			'checkTime' => $this->time,
			'passNum'   => $this->post('passNum') ? self::formattingFigure($this->post('passNum'), 'numPrecision') : '',
		];
		$annotation = [
			'passNum' => '合格数量',
		];
		$rules      = [
			'passNum' => 'required|numeric',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$this->resp['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
			goto resp;
		}
		$where = " id = '$id' ";
		$info  = query(self::table, $where);
		//判断
		if (!$this->power(self::page, "edit")) {
			$this->resp['warn'] = "你没有编辑" . self::title . "的权限";
		} elseif (static::is_null_array($itemIdArr)) {
			$this->resp['warn'] = '未找到质检项目';
		} elseif (static::is_null_array($resultOptionArr)) {
			$this->resp['warn'] = '请选择结果选项';
		} elseif (empty($info['id'])) {
			$this->resp['warn'] = '未找到此委外入库检验单';
		} elseif (!empty($reasonIdArr) && static::is_null_array($reasonNumArr)) {
			$this->resp['warn'] = '请填写不良数量';
		} elseif ($info['state'] !== '待质检') {
			$this->resp['warn'] = '此委外入库检验单不是待质检状态，不能编辑';
		} elseif ($info['num'] < $field['passNum']) {
			$this->resp['warn'] = '合格数量超出了总数量';
		} elseif (round(array_sum($reasonNumArr), 2) != round($info['num'] - $field['passNum'], 2)) {
			$this->resp['warn'] = '不良明细中数量之和不等于总的不良数量';
		} else {
			$this->resp['warn'] = '';
			//判断属于生产计划单的数量是否超过总数量
			foreach ($reasonNumArr as $k => $val) {
				if ($val > $info['num'] - $field['passNum']) {
					$this->resp['warn'] = "不良明细中不良数量和超过了总的不良数量";
					break;
				}
			}
			if (empty($this->resp['warn'])) {
				$this->startTrans();
				$isPass             = true;//事务通过标志
				$this->resp['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
				foreach ($itemIdArr as $k => $nid) {
					$mx = query(self::table . "_item", "id = '$nid'");
					if ($mx['id']) {
						$warn = static::update([
							"table" => self::table . "_item",
							"field" => [
								'options' => $resultOptionArr[$nid],
								'text'    => $itemTextArr[$nid],
							],
							"where" => " id = '$nid'",
						]);
						if (!in_array($warn, ['新增成功', '更新成功'])) {
							$isPass             = false;
							$this->resp['warn'] = $warn;
							break;
						}
					}
				}
				//添加或更新质检不良原因
				if (is_array($reasonIdArr)) {
                    $reasonOptionArr = $reasonIdArr;
					foreach ($reasonIdArr as $k => $nid) {
						$mx                = query(self::table . "_reason", "id = '$nid'");
						$quarantine_reason = query('quarantine_reason', "id = '$reasonOptionArr[$k]'");
						$reasonNumArr[$k]  = self::formattingFigure($reasonNumArr[$k], 'numPrecision');
						if (!empty($mx['id'])) {
							//更新
							$warn = static::update([
								"table" => self::table . "_reason",
								"field" => [
									'reasonId'   => $reasonOptionArr[$k],
									'num'        => $reasonNumArr[$k],
									'dealMethod' => $quarantine_reason['method'],
									'text'       => $mxTextArr[$k],
								],
								"where" => " id = '$nid'",
							]);
						} else {
							//新增
							$warn = static::insert([
								"table" => self::table . "_reason",
								"field" => [
									'id'         => $nid,
									'orderId'    => $id,
									'coid'       => self::$coid,
									'reasonId'   => $reasonOptionArr[$k],
									'num'        => $reasonNumArr[$k],
									'dealMethod' => $quarantine_reason['method'],
									'text'       => $mxTextArr[$k],
								],

							]);
						}
						if (!in_array($warn, ['新增成功', '更新成功'])) {
							$isPass             = false;
							$this->resp['warn'] = $warn;
							break;
						}
					}
				}

				if (in_array($this->resp['warn'], ["新增成功", "更新成功"]) && $isPass) {
					$this->commitTrans();
					delete(array('table' => self::table . "_reason", 'where' => " id not in ('" . implode("','", $reasonIdArr) . "') and orderId = '$id'"));
					//判断此订单所有批次是否都检验完了，如果检验完成，则修改入库单质检状态为已质检
					if (static::total(array('table' => self::table, "where" => " state = '待质检' and sourceId ='$info[sourceId]' and coid = '" . self::$coid . "'")) == 0) {
						update(array('table' => 'inventory', 'field' => ['workFlow' => '已质检'], 'where' => "sourceId = '$info[sourceId]' and classify = 1 and coid = '" . self::$coid . "'"));
					}
					auditingFollow(array(
						"type"   => "委外入库检验单",
						"typeId" => $info['id'],
						"text"   => "【{$this->control['name']}】确认",
					));
					//添加日志
					$type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
					$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
					$this->logText(["type" => self::page, "text" => $text]);
					//返回
					$this->code = 1;
				} else {
					$this->rollback();
				}
			}
		}

		resp:
	}

	/**
	 * 撤回
	 */
	public function cancelEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " id = '$id'");
		$field = [
			'state'     => '待质检',
			'checkId'   => '',
			'checkTime' => '',
		];
		if (!$this->power(self::page, 'cancel')) {
			$this->resp['warn'] = '你还没有撤回权限';
		} elseif (empty($info['id'])) {
			$this->resp['warn'] = '未找到此质检单';
		} elseif ($info['state'] != '已质检') {
			$this->resp['warn'] = '此质检单不是已质检状态，无需撤回';
		} elseif (static::total(array('table' => 'quality_order_reason', 'where' => "orderId = '$id' and state = '已处理'")) > 0) {
			$this->resp['warn'] = '此委外入库检验单已处理，不能撤回';
		} elseif (static::total(array('table' => 'inventory', 'where' => "sourceId = '$info[sourceId]' and state != '待入库' and classify = 1 and coid = '" . self::$coid . "'")) > 0) {
			$this->resp['warn'] = '此委外入库检验单对应的入库单已入库，不能撤回';
		} else {
			$this->resp['warn'] = update(array(
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			));
			if (in_array($this->resp['warn'], ["新增成功", "更新成功"])) {
				update(array('table' => 'inventory', 'field' => ['workFlow' => '待质检'], 'where' => "sourceId = '$info[sourceId]' and classify = 1 and coid = '" . self::$coid . "'"));
				auditingFollow(array(
					"type"   => "委外入库检验单",
					"typeId" => $info['id'],
					"text"   => "【{$this->control['name']}】撤回",
				));
				//添加日志
				$type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$this->code = 1;
			}
		}
		resp:
	}


}
